# -*- coding: utf-8 -*-

from PyQt4 import QtGui,QtCore
from logic_window import Ui_logic_window
from logic import thread_msgs
from widget_moblove import Ui_widget_moblove

class LogicTab(QtGui.QWidget):
    def __init__(self, logicthread, clientinstance):
        QtGui.QWidget.__init__(self)
        self.logic_window = Ui_widget_moblove()
        self.logic_window.setupUi(self)       
        self.logicthread = logicthread
        self.logic_window.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.logic_window.tableWidget.customContextMenuRequested.connect(self.showContextMenu)
        self.userlist =  dict()
        self.logon_dlg = None
        self.clientinstance = clientinstance        
        self.logic_window.label.setText(u"")
    
    def clear_user(self):
        self.logic_window.label.setText(u"当前场景："+str(self.clientinstance.scene))
        self.logic_window.tableWidget.setRowCount(0)
        self.logic_window.tableWidget.clear()
    
    def add_user(self, user):
        self.userlist[user['jid']] = user        
        jiditem = QtGui.QTableWidgetItem("")
        nickitem = QtGui.QTableWidgetItem("")
        sexitem = QtGui.QTableWidgetItem("")
        sceneitem = QtGui.QTableWidgetItem("")
        deskitem = QtGui.QTableWidgetItem("")
        vipitem = QtGui.QTableWidgetItem("")
        busyitem = QtGui.QTableWidgetItem("")
        undisturbeditem = QtGui.QTableWidgetItem("")
        popularityitem = QtGui.QTableWidgetItem("")
        if (user.has_key('jid')):
            if (user['jid']):
                jiditem = QtGui.QTableWidgetItem(user['jid'])                                
        if (user.has_key('nick')):
            if (user['nick']):
                nickitem = QtGui.QTableWidgetItem(user['nick'])
        if (user.has_key('sex')):
            if (user['sex']=="male"):
                sexitem = QtGui.QTableWidgetItem(u'男')
            else:
                sexitem = QtGui.QTableWidgetItem(u'女')
        if (user.has_key('scene')):
            if (user['scene']):
                sceneitem = QtGui.QTableWidgetItem(user['scene']+u'号场景 ')
        if (user.has_key('desk')):
            if (user['desk']):
                deskitem = QtGui.QTableWidgetItem(user['desk']+u'号桌')
        if (user.has_key('vip')):
            if (user['vip']):
                vipitem = QtGui.QTableWidgetItem(user['vip'])
        if (user.has_key('busy')):
            if (user['busy']):
                busyitem = QtGui.QTableWidgetItem(user['busy']) 
        if (user.has_key('undisturbed')):
            if (user['undisturbed']):
                undisturbeditem = QtGui.QTableWidgetItem(user['undisturbed'])
        if (user.has_key('popularity')):
            if (user['popularity']):
                popularityitem = QtGui.QTableWidgetItem(user['popularity'])
        items = [jiditem, nickitem, sexitem, sceneitem, deskitem, vipitem, busyitem, undisturbeditem, popularityitem]
        rowindex = self.logic_window.tableWidget.rowCount()         
        self.logic_window.tableWidget.insertRow(rowindex)
        i = 0
        for item in items:            
            self.logic_window.tableWidget.setItem(rowindex,i,item)
            i = i+1
    
    def showContextMenu(self, point):
        return
        index = self.logic_window.tableWidget.indexAt(point)
        #空白区域不显示菜单
        if index:
            self.rightMenuShow(index.row())

    #创建右键菜单
    def rightMenuShow(self, row):
        rightMenu = QtGui.QMenu(self.logic_window.tableWidget)
        item = self.logic_window.tableWidget.item(row, 0)
        if (item):
            dateitem = QtGui.QAction(u'约Ta:'+unicode(item.text()), self)            
            rightMenu.addAction(dateitem)
            dateitem.setData({"datewith":str(item.text())})
        itemS = self.logic_window.tableWidget.item(row,3)
        itemD = self.logic_window.tableWidget.item(row,4)
        if (itemS and itemD):
            sititem = QtGui.QAction(u'坐下:'+unicode(itemS.text())+"-"+unicode(itemD.text()), self)
            rightMenu.addAction(sititem)
            sititem.setData({"sitwith":str(item.text())})            
            
        rightMenu.triggered.connect(self.onRightMenuItem)
        rightMenu.exec_(QtGui.QCursor.pos())
        
    def onRightMenuItem(self, action):
        data = action.data().toMap()
        if (data.has_key(QtCore.QString('datewith'))):
            jidstr = str(data[QtCore.QString('datewith')].toString())
            self.logicthread.post_msg(thread_msgs.MsgDateRequest(self.clientinstance.jid.as_string(), jidstr))                        
        if (data.has_key(QtCore.QString('sitwith'))):
            jidstr = str(data[QtCore.QString('sitwith')].toString())
            if (self.userlist.has_key(jidstr)):
                scene = self.userlist[jidstr]['scene']
                desk = self.userlist[jidstr]['desk']
                self.logicthread.post_msg(thread_msgs.MsgSitDown(self.clientinstance.jid.as_string(),scene,desk))               
        
    
class LogicUI(QtCore.QObject):
    def __init__(self, logicthread):
        QtCore.QObject.__init__(self)
        self.logicthread = logicthread                
        self.mainwindow = QtGui.QMainWindow()
        self.logic_window = Ui_logic_window()
        self.logic_window.setupUi(self.mainwindow)        
        self.logic_window.tabWidget.removeTab(0)
        self.logic_window.tabWidget.removeTab(0)
            
        QtCore.QObject.connect(self,QtCore.SIGNAL("connected_sig(PyQt_PyObject)"), 
                               self.show_slot)        
        QtCore.QObject.connect(self,QtCore.SIGNAL("disconnected_sig(PyQt_PyObject)"), 
                               self.hide_slot)
        QtCore.QObject.connect(self,QtCore.SIGNAL("add_user(PyQt_PyObject, PyQt_PyObject)"),
                               self.add_user_slot)
        QtCore.QObject.connect(self,QtCore.SIGNAL('clear_user(PyQt_PyObject)'),
                               self.clear_user_slot)
        self.logic_window.tabWidget.tabCloseRequested.connect(self.on_tab_closed)
        self.logic_window.action.triggered.connect(self.menu_clicked)
        self.login_count = 0
        self.usermap =  dict()
        
    def menu_clicked(self):
        if (self.logon_dlg):
            self.logon_dlg.show()
                
    def show(self, clientinstance):        
        self.emit(QtCore.SIGNAL('connected_sig(PyQt_PyObject)'), clientinstance)        
    
    def hide(self, clientinstance):
        self.emit(QtCore.SIGNAL('disconnected_sig(PyQt_PyObject)'), clientinstance)
    
    def clear_user(self,clientinstance):
        self.emit(QtCore.SIGNAL('clear_user(PyQt_PyObject)'),clientinstance)
    
    def add_user(self, user, clientinstance):        
        self.emit(QtCore.SIGNAL('add_user(PyQt_PyObject, PyQt_PyObject)'), user, clientinstance)
    
    def clear_user_slot(self,clientinstance):
        jidstr = clientinstance.jid.as_string()
        if (self.usermap.has_key(jidstr)):
            self.usermap[jidstr].clear_user()
    
    def show_slot(self, clientinstance):
        jidstr = clientinstance.jid.as_string()
        if (self.usermap.has_key(jidstr)):
            print "%r already logined" % jidstr
            return
        self.login_count = self.login_count+1 
        self.logic_window.statusbar.showMessage(u"已登陆"+str(self.login_count)+u"人")
        tab = LogicTab(self.logicthread, clientinstance)        
        self.logic_window.tabWidget.addTab(tab, jidstr)
        self.usermap[jidstr] = tab        
        self.mainwindow.show()
    
    def hide_slot(self, clientinstance):
        jidstr = clientinstance.jid.as_string()
        if (self.usermap.has_key(jidstr)):
            index = self.logic_window.tabWidget.indexOf(self.usermap[jidstr])
            self.logic_window.tabWidget.removeTab(index)            
            self.usermap.pop(jidstr)
            self.login_count = self.login_count-1
            self.logic_window.statusbar.showMessage(u"已登陆"+str(self.login_count)+u"人")
        else:
            print "%r did not logined" % jidstr
            return 
            
        
    def add_user_slot(self, user, clientinstance):        
        jidstr = clientinstance.jid.as_string()
        if (self.usermap.has_key(jidstr)):
            self.usermap[jidstr].add_user(user)
        else:
            print "%r already did not logined" % jidstr           
    
    
    def on_tab_closed(self, index):
        clientinstance = self.logic_window.tabWidget.widget(index).clientinstance
        if (clientinstance):            
            jidstr = clientinstance.jid.as_string()
            print(jidstr+" close event")
            self.logicthread.post_msg(thread_msgs.MsgDisconnect(jidstr))        
    